package net.acnull.arpg.effect;

import net.acnull.arpg.Main;
import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;

import java.util.ArrayList;
import java.util.List;

class DynamicEffectManager{

    private static final DynamicEffectManager manager=new DynamicEffectManager();

    private long timer;
    private final List<DynamicEffect> list;
    private final List<DynamicEffect> waitList;

    public static DynamicEffectManager getInstance(){
        return manager;
    }

    private DynamicEffectManager(){
        list=new ArrayList<>();
        waitList=new ArrayList<>();
        Bukkit.getScheduler().runTaskTimer(Main.getPlugin(Main.class),()->{
            timer++;
            List<DynamicEffect> effects=new ArrayList<>();
            list.addAll(waitList);
            waitList.clear();
            for(DynamicEffect effect:list){
                if(timer%effect.getRange()==0){
                    if(effect instanceof IDamage){
                        if(effect instanceof IAOEDamage){
                            int radius = ((IAOEDamage) effect).getRadius();
                            if(((IAOEDamage) effect).isCall()) {
                                effect.getLocation().getWorld()
                                        .getNearbyEntities(effect.getLocation(), radius, 0.5, radius).stream()
                                        .filter(entity -> entity != ((IDamage) effect).getOwner() && entity instanceof LivingEntity && entity.getLocation().distance(effect.getLocation()) < radius)
                                        .forEach(entity -> ((IDamage) effect).onDamage((LivingEntity) entity));
                            }
                        }else {
                            effect.getLocation().getWorld()
                                    .getNearbyEntities(effect.getLocation(), 0.5, 0.2, 0.5).stream()
                                    .filter(entity -> entity != ((IDamage) effect).getOwner() && entity instanceof LivingEntity)
                                    .forEach(entity -> ((IDamage) effect).onDamage((LivingEntity) entity));
                        }
                    }
                    if(!effect.next()||effect.getLocation().getBlockY()<0){
                        effects.add(effect);
                    }
                }
            }
            for (DynamicEffect effect:effects){
                list.remove(effect);
            }
        },1,1);
    }

    public void addEffect(DynamicEffect effect){
        waitList.add(effect);
    }

}
